package com.mvc.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

import com.common.utils.IOUtils;
import com.common.utils.JsonUtil;
import com.google.gson.reflect.TypeToken;
import com.jfinal.kit.PathKit;
import com.mvc.model.Venue;
import com.mvc.request.FinalData;
import com.mvc.request.ReqSendMessage;
import com.mvc.service.MessageService;

// 定时任务
public class TimeTaskService {

	private MessageService messageService = new MessageServiceImpl();

	// 暂停时间
	private long sleep = 0;
	// 上次操作时间
	private long lastTime = 0;
	
	private  ScheduledExecutorService scheduledExecutorService;
	
	public TimeTaskService()
	{
		ThreadFactory threadFactory = new ThreadFactory() {
			
			@Override
			public Thread newThread(Runnable r) {
				Thread thread = Executors.defaultThreadFactory().newThread(r);
				//线程标记为守护线程
				thread.setDaemon(true);
				return thread;
			}
		};
		scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(threadFactory);
	}
	
	public void start() {
		// 第二个参数为首次执行的延时时间，第三个参数为定时执行的间隔时间 【秒】
		scheduledExecutorService.scheduleAtFixedRate(runnable, 1, 60,
				TimeUnit.SECONDS);
	}


	private Runnable runnable = new Runnable() {

		@Override
		public void run() {

			Calendar cal = Calendar.getInstance();
			int hour = cal.get(Calendar.HOUR_OF_DAY);
			
			if (hour < 8 || hour > 22)
			{
				return;
			}
			
			long time = cal.getTimeInMillis() / (1000*60);
			if (time - lastTime < sleep) {
				return;
			}
			sleep  = 	(long) (Math.random()*20);
			lastTime = time;

			System.out.println("下次留言间隙：sleep="+sleep);
			// 自动产生留言
			List<String> dataList=null;
			try {
				dataList = json();
			} catch (IOException e) {
				e.printStackTrace();
			}
		
			if (dataList == null || dataList.isEmpty()) {
				return;
			}

			List<Venue> listVenues = getVenueList();
			if (listVenues == null || listVenues.isEmpty()) {
				return;
			}
			int indexContent = (int) ((dataList.size() - 1) * Math.random());

			int indexVenue = (int) ((listVenues.size() - 1) * Math.random());

			ReqSendMessage msg = new ReqSendMessage();
			FinalData finalData = new FinalData();
			finalData.setCode(100);
			finalData.setMac("112233445566");
			finalData.setType("web");
			msg.setFinalData(finalData);
			msg.setUserId(10000);
			msg.setType(0);

			msg.setContent(dataList.get(indexContent));
			msg.setVenueId(listVenues.get(indexVenue).getInt(
					Venue.TableField.ID));

			messageService.create(msg);
		}
	};

	List<Venue> getVenueList() {
		return Venue.dao.find("select  *  from venue where  "+Venue.TableField.TYPE+"=3");
	}

	// 范文
	private List<String> json() throws IOException {
		String ehcacheConf = PathKit.getWebRootPath() + File.separator
				+ "WEB-INF" + File.separator + "ly_config.json";
		FileInputStream fin = null;

		fin = new FileInputStream(ehcacheConf);
		String josnString = IOUtils.toString(fin);

		return JsonUtil.fromJson(josnString, new TypeToken<List<String>>() {
		}.getType());

	}
}
